package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingStressChangeInfo;
import com.ruoyi.ring.domain.dto.RingStressChangeInfoAddDTO;
import com.ruoyi.ring.service.IRingStressChangeInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 压力信息 （APP）
 */
@RestController
@RequestMapping("/ring/app/ring_stress_change_info")
public class AppStressChangeInfoController extends BaseController
{
    @Resource
    private IRingStressChangeInfoService ringStressChangeInfoService;


    /**
     * 上报压力信息-app
     */
    @Log(title = "上报压力信息", businessType = BusinessType.INSERT)
    @PostMapping("/add-stress-change-info")
    public AjaxResult addStressChangeInfo(@RequestBody RingStressChangeInfoAddDTO addDTO)
    {
        String deviceSn = addDTO.getDeviceSn();
        try {
            List<RingStressChangeInfoAddDTO.StressDTO> stressDTOList = addDTO.getStress();
            stressDTOList.forEach(stressDTO -> {
                Date dailyValue = stressDTO.getDailyValue();
                RingStressChangeInfo stressChangeInfo = ringStressChangeInfoService.selectOneRingStressChangeInfo(Builder.of(RingStressChangeInfo::new).
                        with(RingStressChangeInfo::setDeviceSn, deviceSn).
                        with(RingStressChangeInfo::setRecordTime, dailyValue).build());
                RingStressChangeInfo ringStressChangeInfo = Convert.convert(RingStressChangeInfo.class,stressDTO);
                if(stressChangeInfo != null){
                    ringStressChangeInfo.setId(stressChangeInfo.getId());
                    ringStressChangeInfo.setDeviceSn(deviceSn);
                    ringStressChangeInfo.setRecordTime(dailyValue);
                    ringStressChangeInfo.setUserId(SecurityUtils.getUserId());
                    ringStressChangeInfoService.updateRingStressChangeInfo(ringStressChangeInfo);
                }else {
                    ringStressChangeInfo.setDeviceSn(deviceSn);
                    ringStressChangeInfo.setRecordTime(dailyValue);
                    ringStressChangeInfo.setUserId(SecurityUtils.getUserId());
                    ringStressChangeInfoService.insertRingStressChangeInfo(ringStressChangeInfo);
                }
            });
            return AjaxResult.success();
        }catch (Exception e){
            throw new RuntimeException("上报压力信息失败！");
        }

    }
}
